#include "GetData.h"



// // 声明引用外部DefineData里的变量
// Define_Data Data;

const String language = "zh-Hans";  // 请求语言
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "ntp1.aliyun.com", 8 * 3600, 60000); //udp，服务器地址，时间偏移量，更新间隔


//dth11定义
#define DHTTYPE DHT11   // DHT 11
#define DHTPIN D1       //引脚D1
DHT dht(DHTPIN, DHTTYPE);
//******  dth11服务初始化 ******
void DHT11_init()
{
  dht.begin();
}

//******  ntp时间服务初始化 ******
void NTP_init()
{
   timeClient.begin();
}

void Get_Time()
{
  // display_bitmap_bottom(Bitmap_wlq4, "获取时间");
  //获取时间
  uint8_t update_count = 0;
  while (timeClient.update() == 0 && update_count < 3)
  {
    Serial.print("NTP超时计数:"); 
    Serial.println(update_count);
    delay(100);
    if(update_count == 2)
    {
      NTPClient timeClient(ntpUDP, "s2k.time.edu.cn", 8 * 3600, 60000);  
      timeClient.begin();
    }
    else if(update_count == 3)
    {
      NTPClient timeClient(ntpUDP, "1d.time.edu.cn", 8 * 3600, 60000);  
      timeClient.begin();
    }
    update_count++;
  }
  if (update_count < 3)
  {
    Data.RTC_hour = timeClient.getHours();
    Data.RTC_minute =timeClient.getMinutes();
    // ESP.rtcUserMemoryWrite(RTCdz_hour, &RTC_hour, sizeof(RTC_hour));    //向RCT写向RTC存储区写数据
    Serial.print("获取时间:"); 
    Serial.println(timeClient.getFormattedTime());
    timeClient.end();
    // display_partialLine(7, "NTP,OK!");
    Data.RTC_ntpTimeError = 0;
  }
  else
  {
    // String a; String b;
    // a = actual.last_update[11];
    //  b = actual.last_update[12]; //String转char
    // RTC_hour = atoi(a.c_str()) * 10; //char转int
    // RTC_hour += atoi(b.c_str()) + 1;
    // // ESP.rtcUserMemoryWrite(RTCdz_hour, &RTC_hour, sizeof(RTC_hour));
    // Serial.print("获取时间："); 
    // Serial.println(RTC_hour);
    // // display_partialLine(7, "获取NTP时间失败,改用天气时间");
    Data.RTC_ntpTimeError = 1;
  }
}

void Get_TianQi()
{    
    String url_ActualWeather;    //天气实况地址
    String url_FutureWeather;    //未来天气地址
    String url_LifeIndex;        //生活指数地址
    String weatherKey_s = eepUserSet.weatherKey; //秘钥
    String city_s = eepUserSet.city;             //城市
    //"http://api.seniverse.com/v3/weather/now.json?key=S6pG_Q54kjfnBAi6i&location=深圳&language=zh-Hans&unit=c"
    //拼装天气实况API地址
    url_ActualWeather = "http://api.seniverse.com/v3/weather/now.json";
    url_ActualWeather += "?key=" + weatherKey_s + "&location=" + city_s + "&language=" + language + "&unit=c";
    /*
    //https://api.seniverse.com/v3/weather/daily.json?key=S6pG_Q54kjfnBAi6i&location=深圳&language=zh-Hans&unit=c&start=0&days=3
    //拼装实况未来API地址
    url_FutureWeather = "http://api.seniverse.com/v3/weather/daily.json";
    url_FutureWeather += "?key=" + weatherKey_s + "&location=" + city_s + "&language=" + language + "&start=0" + "&days=3";

    //https://api.seniverse.com/v3/life/suggestion.json?key=S6pG_Q54kjfnBAi6i&location=shanghai&language=zh-Hans
    //拼装生活指数API地址
    url_LifeIndex = "http://api.seniverse.com/v3/life/suggestion.json";
    url_LifeIndex += "?key=" + weatherKey_s + "&location=" + city_s;
    */
    uint8_t cs_count = 0; //重试计数
    uint8_t cs_max = 2;   //重试次数
    /*
    display_partialLine(7, "获取生活指数");
    while (ParseLifeIndex(callHttp(url_LifeIndex), &life_index) == 0 && cs_count < cs_max) //获取生活指数
    {
      cs_count++;
    }
    */
    cs_count = 0;
    // display_bitmap_bottom(Bitmap_xiaohei, "获取天气实况数据中");
    while (ParseActualWeather(callHttp(url_ActualWeather), &actual) == 0 && cs_count < cs_max)
    {
      cs_count++;
    }
    /*
    cs_count = 0;
    // display_bitmap_bottom(Bitmap_byx, "获取未来天气数据中");
    display_partialLine(6, "获取未来天气数据中");
    while (ParseFutureWeather(callHttp(url_FutureWeather), &future) == 0 && cs_count < cs_max)
    {
      cs_count++;
    }
    */
}

void Get_Dht11data()
{
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  Data.DHT11_Humidity = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  Data.DHT11_Temperature = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);
  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  // float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);
  Data.Heat_index = dht.computeHeatIndex(t, h, false);

  Serial.print(F("Humidity: "));
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print(F("°C "));
  Serial.print(f);
  Serial.print(F("°F  Heat index: "));
  Serial.print(hic);
  Serial.print(F("°C "));
  // Serial.print(hif);
  // Serial.println(F("°F"));
}